/**
 * 微信开放数据域
 * 使用 Canvas2DAPI 在 SharedCanvas 渲染一个排行榜，
 * 并在主域中渲染此 SharedCanvas
 */

//获取所有好友的托管数据
wx.getFriendCloudStorage({
  keyList: ["score"],
  success: res => {
    console.log(res);
    myData = res.data;
    //删除空数据玩家
    for (let i = 0; i < myData.length; i++) {
      if (myData[i].KVDataList.length < 1) {
        myData.splice(i, 1)
      }
    }
    //排序
    for (let i = 0; i < myData.length - 1; i++) {
      for (let j = 0; j < myData.length - 1 - i; j++) {
        if (myData[j].KVDataList[0].value * 1 < myData[j + 1].KVDataList[0].value * 1) {
          var lin = myData[j];
          myData[j] = myData[j + 1];
          myData[j + 1] = lin;
        }
      }
    }
    totalGroup = [];
    for (let i = 0; i < myData.length; i++) {
      if (myData[i].KVDataList.length < 1) {
        continue;
      }
      /**头像图片*/
      let image = wx.createImage();
      image.src = myData[i].avatarUrl; //这个是好友数据中的avatarUrl   
      totalGroup.push({
        key: i + 1,
        name: myData[i].nickname,
        url: image,
        scroes: "得分" + myData[i].KVDataList[0].value
      })
    }
    renderDirty = true;
  },
  fail: res => {
    console.log(res.data);
  }
});
/**friend data */
var myData;

/**接收主域信息 */
wx.onMessage(data => {
  console.log("主域传递信息：");
  console.log(data);

  if (data.score != null) {
    // wx.getUserCloudStorage({
    //   keyList: ['score'],
    //   success: res => {
    //     console.log("用户历史数据：");
    //     console.log(res);
    //之前是否有托管数据
    // if (res.KVDataList.length >= 1) {
    //   if (parseInt(res.KVDataList[0].value) < parseInt(data.score)) {
    //     wx.setUserCloudStorage({
    //       KVDataList: [{
    //         key: 'score',
    //         value: data.score
    //       }],
    //       success: res => {
    //         console.log("托管数据成功" + res);
    //       },
    //       fail: res => {
    //         console.log("托管数据失败" + res);
    //       }
    //     });
    //   }
    // } else {
    wx.setUserCloudStorage({
      KVDataList: [{
        key: 'score',
        value: data.score
      }],
      success: res => {
        console.log("托管数据成功" + res);
      },
      fail: res => {
        console.log("托管数据失败" + res);
      }
    });
    // }
    // }
    //})
  }

  if (data.isDisplay) {
    console.log("显示排行榜");
    //获取所有好友的托管数据
    wx.getFriendCloudStorage({
      keyList: ["score"],
      success: res => {
        console.log(res);
        myData = res.data;
        //删除空数据玩家
        for (let i = 0; i < myData.length; i++) {
          if (myData[i].KVDataList.length < 1) {
            myData.splice(i, 1)
          }
        }
        //排序
        for (let i = 0; i < myData.length - 1; i++) {
          for (let j = 0; j < myData.length - 1 - i; j++) {
            if (myData[j].KVDataList[0].value * 1 < myData[j + 1].KVDataList[0].value * 1) {
              var lin = myData[j];
              myData[j] = myData[j + 1];
              myData[j + 1] = lin;
            }
          }
        }
        totalGroup = [];
        for (let i = 0; i < myData.length; i++) {
          if (myData[i].KVDataList.length < 1) {
            continue;
          }
          /**头像图片*/
          let image = wx.createImage();
          image.src = myData[i].avatarUrl; //这个是好友数据中的avatarUrl   
          totalGroup.push({
            key: i + 1,
            name: myData[i].nickname,
            url: image,
            scroes: "得分" + myData[i].KVDataList[0].value
          })
        }
        renderDirty = true;
      },
      fail: res => {
        console.log(res.data);
      }
    });
  }
});

/**
 * 资源加载组，将所需资源地址以及引用名进行注册
 * 之后可通过assets.引用名方式进行获取
 */
var assets = {
  //icon: "openDataContext/assets/icon.png",
  // box: "openDataContext/assets/box.png",
  //panel: "openDataContext/assets/panel.png",
  // button: "openDataContext/assets/button.png",
  //title: "openDataContext/assets/rankingtitle.png",

  shang: "openDataContext/assets/shangbian.png",
  xia: "openDataContext/assets/xiabian.png",
  di: "openDataContext/assets/dibian.png",
  logo: "openDataContext/assets/logo.png",
  shangye: "openDataContext/assets/shangye.png",
  xiaye: "openDataContext/assets/xiaye.png",
};
/**
 * canvas 大小
 * 这里暂时写死
 * 需要从主域传入
 */
let canvasWidth;
let canvasHeight;

/**
 * 加载资源函数
 * 理论上只需要加载一次，且在点击时才开始加载
 * 最好与canvasWidht和canvasHeight数据的传入之后进行
 */
preloadAssets();

//获取canvas渲染上下文
var context = sharedCanvas.getContext("2d");
context.globalCompositeOperation = "source-over";

/**
 * 所有头像数据
 * 包括姓名，头像图片，得分
 * 排位序号i会根据parge*perPageNum+i+1进行计算
 */
let totalGroup = [{
    key: 1,
    name: "1111111111",
    url: assets.di,
    scroes: 10000
  },
  {
    key: 2,
    name: "2222222222",
    url: assets.di,
    scroes: 9000
  },
  {
    key: 3,
    name: "3333333",
    url: assets.di,
    scroes: 8000
  },
];

/**
 * 创建排行榜
 */
function drawRankPanel() {
  //绘制背景
  context.drawImage(assets.di, offsetX_rankToBorder, offsetY_rankToBorder, RankWidth, RankHeight);
  /**标题 */
  let title = assets.logo;
  //根据标题的宽高计算一下位置;
  let titleX = (stageWidth - title.width) / 2 - 21 * scaleHigh;
  let titleY = offsetY_rankToBorder * 1.5;
  //绘制标题
  context.drawImage(title, titleX, titleY, 111 * scaleHigh, 42 * scaleHigh);

  //获取当前要渲染的数据组
  let start = perPageMaxNum * page;
  currentGroup = totalGroup.slice(start, start + perPageMaxNum);
  //创建头像Bar
  drawRankByGroup(currentGroup);
  //创建按钮
  drawButton()
}
/**
 * 根据屏幕大小初始化所有绘制数据
 */
function init() {
  //排行榜绘制数据初始化
  //RankWidth = stageWidth * 11 / 15;
  RankWidth = 840 * scaleHigh;
  //RankHeight = stageHeight * 27 / 30;
  RankHeight = 590 * scaleHigh;
  barWidth = RankWidth * 23 / 30;
  barHeight = RankHeight / (perPageMaxNum + 2) - 10;
  offsetX_rankToBorder = (stageWidth - RankWidth) / 2;
  offsetY_rankToBorder = (stageHeight - RankHeight) / 2;
  preOffsetY = (RankHeight - barHeight) / (perPageMaxNum + 2) + 5;

  startX = (stageWidth - barWidth) / 2 - 20;
  startY = offsetY_rankToBorder + preOffsetY * 1.5;
  avatarSize = barHeight - 10;
  intervalX = barWidth / 15;
  textOffsetY = (barHeight + fontSize) / 2;
  textMaxSize = 250*scaleHigh;
  indexWidth = context.measureText("99").width;

  //按钮绘制数据初始化
  buttonWidth = barWidth / 10;
  buttonHeight = barHeight / 2;
  buttonOffset = RankWidth / 3;
  lastButtonX = nextButtonX = startX + barWidth + 10
  //nextButtonX = offsetX_rankToBorder + barWidth //+ 2 * buttonOffset;
  nextButtonY = startY + 5 * preOffsetY - textOffsetY - 10;
  lastButtonY = startY + preOffsetY - textOffsetY
  let data = wx.getSystemInfoSync();
  canvasWidth = data.windowWidth;
  canvasHeight = data.windowHeight;
}

/**
 * 创建两个点击按钮
 */
function drawButton() {
  context.drawImage(assets.xiaye, nextButtonX, nextButtonY, buttonWidth, buttonHeight);
  context.drawImage(assets.shangye, lastButtonX, lastButtonY, buttonWidth, buttonHeight);

}


/**
 * 根据当前绘制组绘制排行榜
 */
function drawRankByGroup(currentGroup) {
  for (let i = 0; i < currentGroup.length; i++) {
    let data = currentGroup[i];
    drawByData(data, i);
  }
}

/**
 * 根据绘制信息以及当前i绘制元素
 */
function drawByData(data, i) {
  let x = startX;
  //绘制底框
  if (i % 2 == 0) {
    context.drawImage(assets.shang, startX, startY + i * preOffsetY, barWidth, barHeight);
  } else {
    context.drawImage(assets.xia, startX, startY + i * preOffsetY, barWidth, barHeight);
  }
  x += 50*scaleHigh;
  //设置字体
  context.font = fontSize * scaleHigh + "px Arial";
  context.fillStyle = "#ffffff"
  //绘制序号
  context.fillText(data.key, x, startY + i * preOffsetY + textOffsetY, textMaxSize);
  x += indexWidth + intervalX;
  //绘制头像
  context.drawImage(data.url, x, startY + i * preOffsetY + (barHeight - avatarSize) / 2, avatarSize, avatarSize);
  x += avatarSize + intervalX;
  //绘制名称
  context.fillText(data.name, x, startY + i * preOffsetY + textOffsetY, textMaxSize);
  x += textMaxSize + intervalX;
  //绘制分数
  context.fillText(data.scroes, x, startY + i * preOffsetY + textOffsetY, textMaxSize);

}

/**
 * 点击处理
 */
function onTouchEnd(event) {
  let x = event.clientX * sharedCanvas.width / canvasWidth;
  let y = event.clientY * sharedCanvas.height / canvasHeight;
  if (x > lastButtonX && x < lastButtonX + buttonWidth &&
    y > lastButtonY && y < lastButtonY + buttonHeight) {
    //在last按钮的范围内
    if (page > 0) {
      buttonClick(0);

    }
  }
  if (x > nextButtonX && x < nextButtonX + buttonWidth &&
    y > nextButtonY && y < nextButtonY + buttonHeight) {
    //在next按钮的范围内
    if ((page + 1) * perPageMaxNum < totalGroup.length) {
      buttonClick(1);
    }
  }

}
/**
 * 根据传入的buttonKey 执行点击处理
 * 0 为上一页按钮
 * 1 为下一页按钮
 */
function buttonClick(buttonKey) {
  let old_buttonY;
  if (buttonKey == 0) {
    //上一页按钮
    old_buttonY = lastButtonY;
    lastButtonY += 10;
    page--;
    renderDirty = true;
    console.log('上一页');
    setTimeout(() => {
      lastButtonY = old_buttonY;
      //重新渲染必须标脏
      renderDirty = true;
    }, 100);
  } else if (buttonKey == 1) {
    //下一页按钮
    old_buttonY = nextButtonY;
    nextButtonY += 10;
    page++;
    renderDirty = true;
    console.log('下一页');
    setTimeout(() => {
      nextButtonY = old_buttonY;
      //重新渲染必须标脏
      renderDirty = true;
    }, 100);
  }

}

/////////////////////////////////////////////////////////////////// 相关缓存数据

/**********************数据相关***************************/

/**
 * 渲染标脏量
 * 会在被标脏（true）后重新渲染
 */
let renderDirty = true;

/**
 * 当前绘制组
 */
let currentGroup = [];
/**
 * 每页最多显示个数
 * 建议大于等于4个
 */
let perPageMaxNum = 5;
/**
 * 当前页数,默认0为第一页
 */
let page = 0;
/***********************绘制相关*************************/
/**
 * 舞台宽
 */
let stageWidth;
/**舞台高 */
let stageHeight;
/**
 * 排行榜宽
 */
let RankWidth;
/**排行榜高 */
let RankHeight;

/**
 * 每个头像条目的宽
 */
let barWidth;
/**每个头像条目的高 */
let barHeight;
/**
 * 条目与排行榜边界的水平距离
 */
let offsetX_barToRank
/**
 * 排行榜内容起始点X
 */
let startX;
/**
 * 排行榜内容起始点Y
 */
let startY;
/**
 * 每行Y轴间隔offsetY
 */
let preOffsetY;
/**
 * 按钮宽
 */
let buttonWidth;
/**按钮高 */
let buttonHeight;
/**
 * 上一页按钮X坐标
 */
let lastButtonX;
/**
 * 下一页按钮x坐标
 */
let nextButtonX;
/**
 * 上一页按钮y坐标
 */
let lastButtonY;
/**
 * 下一页按钮y坐标
 */
let nextButtonY;
/**
 * 两个按钮的间距
 */
let buttonOffset;

/**
 * 字体大小
 */
let fontSize = 25;
/**
 * 文本文字Y轴偏移量
 * 可以使文本相对于图片大小居中
 */
let textOffsetY;
/**
 * 头像大小
 */
let avatarSize;
/**
 * 名字文本最大宽度，名称会根据
 */
let textMaxSize;
/**
 * 排行榜内容间隔X
 */
let intervalX;
/**
 * 排行榜与舞台边界的水平距离
 */
let offsetX_rankToBorder;
/**
 * 排行榜与舞台边界的竖直距离
 */
let offsetY_rankToBorder;
/**
 * 绘制排名的最大宽度
 */
let indexWidth;
/**缩放宽比例 */
let scaleWidth;
/**缩放高比例 */
let scaleHigh;

//////////////////////////////////////////////////////////
/**
 * 监听点击
 */
wx.onTouchEnd((event) => {
  var l = event.changedTouches.length;
  for (var i = 0; i < l; i++) {
    onTouchEnd(event.changedTouches[i]);
  }
});


/**
 * 资源加载
 */
function preloadAssets() {
  var preloaded = 0;
  var count = 0;
  for (var asset in assets) {
    count++;
    var img = wx.createImage();
    img.onload = function() {
      preloaded++;
      if (preloaded == count) {
        setTimeout(function() {
          createScene();
        }, 500);
      }
    }
    img.src = assets[asset];
    assets[asset] = img;
  }
}
/**
 * 绘制屏幕
 * 这个函数会在加载完所有资源之后被调用
 */
function createScene() {
  if (sharedCanvas.width && sharedCanvas.height) {
    console.log('初始化完成')
    stageWidth = sharedCanvas.width;
    stageHeight = sharedCanvas.height;
    scaleWidth = stageWidth / 1136;
    scaleHigh = stageHeight / 640;
  } else {
    console.log(`sharedCanvas.width:${sharedCanvas.width}    sharedCanvas.height：${sharedCanvas.height}`)
  }
  init();
  requestAnimationFrame(loop);
}
/**
 * 循环函数
 * 每帧判断一下是否需要渲染
 * 如果被标脏，则重新渲染
 */
function loop() {
  if (renderDirty) {
    console.log(`stageWidth :${stageWidth}   stageHeight:${stageHeight}`)
    context.setTransform(1, 0, 0, 1, 0, 0);
    context.clearRect(0, 0, sharedCanvas.width, sharedCanvas.height);
    drawRankPanel();
    renderDirty = false;
  }
  requestAnimationFrame(loop);
}